package com.bootdo.coach.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.coach.domain.TabAgent;
import com.bootdo.coach.service.TabAgentService;
import com.bootdo.coach.vo.TabAgentVo;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.AgentMD5;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;

import io.swagger.annotations.ApiOperation;

/**
 * 下级代理商管理
 * @author Administrator
 *
 */
@RequestMapping("/coach/subAgent")
@Controller
public class SubAgentController extends BaseController{
	private String prefix = "coach/subAgent";

	@Autowired
	private TabAgentService agentService;
	
	@Autowired
	private UserService userService;
	
	//下级代理商=============>>>开始
	
	@RequiresPermissions("coach:subAgent:subAgent")
	@GetMapping("subAgent")
	String subAgent(Model model) {
		return prefix + "/subAgent";
	}
	
	@ApiOperation(value="获取下级代理商列表", notes="")
	@ResponseBody
	@GetMapping("/subAgentList")
	@RequiresPermissions("coach:subAgent:subAgent")
	public PageUtils subAgentList(@RequestParam Map<String, Object> params) {
		int total = 0;
		List<TabAgentVo> subAgentList = new ArrayList<TabAgentVo>();
		// 找出当前用户的代理商
		String bg_account = getUser().getUsername();
		TabAgent curAgent = agentService.findAgent(bg_account, null);
		if (curAgent == null) {
			PageUtils pageUtil = new PageUtils(subAgentList, total);
			return pageUtil;
		}
		// 查询列表数据
		Query query = new Query( params );
		query.put("higher_agent_id", curAgent.getAgentId());
		subAgentList = agentService.list(query);
		total = agentService.count(query);
		PageUtils pageUtil = new PageUtils(subAgentList, total);
		return pageUtil;
	}
	
	@RequiresPermissions("coach:subAgent:subAgentAdd")
	@Log("添加下级代理商")
	@GetMapping("/subAgentAdd")
	String subAgentAdd() {
		return prefix + "/subAgentAdd";
	}
	
	@RequiresPermissions("coach:subAgent:subAgentEdit")
	@Log("编辑下级代理商")
	@GetMapping("/subAgentEdit/{agentId}")
	String subAgentEdit(Model model, @PathVariable("agentId") Long agentId) {
		TabAgent agent = agentService.selectByPrimaryKey(agentId);
		model.addAttribute("agent", agent);
		return prefix+"/subAgentEdit";
	}
	
	@RequiresPermissions("coach:subAgent:subAgentAdd")
	@Log("保存下级代理商")
	@PostMapping("/saveSubAgent")
	@ResponseBody
	R saveSubAgent(TabAgent agent) {
		// 找出当前用户的代理商
		String bg_account = getUser().getUsername();
		TabAgent curAgent = agentService.findAgent(bg_account, null);
		if (curAgent == null) {
			return R.error("当前登录用户不是代理商");
		}
		if (curAgent.getLevel().intValue() == 2) {
			return R.error("当前登录用户是三级代理商，不能增加下级代理商");
		}

		agent.setHigherAgentId(curAgent.getAgentId());
		agent.setLevel(curAgent.getLevel().intValue() + 1);// 设置级别
		String oldpwd = agent.getBgPassword();
		agent.setBgPassword(AgentMD5.md5(agent.getBgPassword()));
		
		if (agentService.insertSelective(agent) > 0) {
			addUser(agent.getAgentName(), agent.getBgAccount(), oldpwd);
			return R.ok();
		}
		return R.error();
	}
	
	@RequiresPermissions("coach:subAgent:subAgentEdit")
	@Log("更新下级代理商")
	@PostMapping("/updateSubAgent")
	@ResponseBody
	R updateSubAgent(TabAgent agent) {
		
		TabAgent temp = agentService.selectByPrimaryKey(agent.getAgentId());
		if (!temp.getBgPassword().equals(agent.getBgPassword())) {
			agent.setBgPassword(AgentMD5.md5(agent.getBgPassword()));
		}
		
		if (agentService.updateByPrimaryKeySelective(agent) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 查询代理商名称是否存在
	 * @param params
	 * @return
	 */
	@PostMapping("/exitAgentName")
	@ResponseBody
	boolean exitAgentName(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !agentService.exitAgentName(params);
	}
	
	/**
	 * 查询后台登录账号是否存在
	 * @param params
	 * @return
	 */
	@PostMapping("/exitBgAccount")
	@ResponseBody
	boolean exitBgAccount(@RequestParam Map<String, Object> params) {
		// 存在，不通过，false
		return !agentService.exitBgAccount(params);
	}
	
	/**
	 * 增加后台账号
	 * @param agentName
	 * @param userName
	 * @param password
	 */
	private void addUser(String agentName, String userName, String password){
		UserDO user = new UserDO();
		user.setUsername(userName);
		user.setPassword(MD5Utils.encrypt(userName, password));
		user.setName(agentName);
		List<Long> roleIds = new ArrayList<Long>();
		roleIds.add(60l);
		user.setRoleIds(roleIds);
		user.setStatus(1);
		//{"deptName":"","email":"lifaqiu@163.com","name":"测试","password":"25bb7c42604b0e7aba7bcae50e7762a9","roleIds":[60],"status":1,"username":"test"}
		userService.save(user);
	}
}
